<?php
require_once(_PS_MODULE_DIR_.'prestatheme/controllers/admin/AdminPrestathemeEditorController.php');
require_once(_PS_MODULE_DIR_.'prestatheme/models/ConfigTab.php');

class AdminConfigTabController extends ModuleAdminController
{
    protected $editor;
    
	public function __construct()
	{
		$this->table      = 'pt_config_tab';
		$this->identifier = 'id_tab';
		$this->className  = 'ConfigTab';
		$this->lang       = true;
		
		$this->context = Context::getContext();
		
		$this->addRowAction('add');
		$this->addRowAction('edit');
		$this->addRowAction('delete');
		
		$this->bulk_actions = array(
			'delete' => array(
				'text' => $this->l('Delete selected'), 
				'confirm' => $this->l('Delete selected items?')
			)
		);

		$this->_select = '
    		CONCAT(c.`code`, \' \', c.`version`) AS `editor`';

		$this->_join = '
    		LEFT JOIN `'._DB_PREFIX_.'pt_theme_editor` e ON (e.`id_editor` = a.`id_editor`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms` c ON (c.`id_cms` = e.`id_cms`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms_lang` cl ON (c.`id_cms` = cl.`id_cms` AND cl.`id_lang` = '.(int)$this->context->language->id.')';
		
		$this->fields_list = array(
			'id_tab' => array(
				'title' => $this->l('ID'), 
				'align' => 'center', 
				'width' => 25
			),
			'label' => array(
				'title' => $this->l('Tab name'), 
				'align' => 'center', 
			),
			'editor' => array(
				'title' => $this->l('Target CMS'), 
				'align' => 'center', 
			),
            'date_add' => array(
                'title' 	=> $this->l('Created On'),
                'type' 	=> 'date'
            ),
            'date_upd' => array(
                'title' 	=> $this->l('Last update On'),
                'type' 	=> 'date'
            ),
            'position' => array(
                'title' => $this->l('Position'),
                'width' => 40,
                'filter_key' => 'position',
                'align' => 'center',
                'position' => 'position'
            ),
			'active' => array(
				'title' => $this->l('Enabled'), 
				'width' => 25, 
				'align' => 'center', 
				'active' => 'status', 
				'type' => 'bool', 
				'orderby' => false
			),
		);
        
        /*
		// The controller can't be call directly
		// In this case, AdminPrestathemeEditorController::getCurrentEditor() is null
		if (!AdminPrestathemeEditorController::getCurrentEditor())
		{
			$this->redirect_after = '?controller=AdminPrestathemeEditor&token='.Tools::getAdminTokenLite('AdminPrestathemeEditor');
			$this->redirect();
		}
        */

		$this->editor = AdminPrestathemeEditorController::getCurrentEditor();
        if (!empty($this->editor->id))
            $this->_filter = 'AND a.`id_editor` = '.(int)$this->editor->id;
        
		parent::__construct();
	}

	/**
	 * AdminController::initContent() override
	 * @see AdminController::initContent()
	 */
	public function initContent()
	{
		$this->initToolbar();
        $this->toolbar_scroll = false;
		switch ($this->display)
		{
			// @todo defining default buttons
			case 'add':
			case 'edit':
                $back = null;
                if (!empty($this->configTab->id)) {
                    $back = self::$currentIndex.'&id_editor='. $this->editor->id .'&token='.$this->token;
            		$this->toolbar_btn['back'] = array(
            			'href' => $back,
            			'desc' => $this->l('Back to the editor')
            		);
                }
                
                if (empty($back))
                    unset($this->toolbar_btn['back']);
            		
                break;
		}
	}

	/**
	 * Modifying initial getList method to display position feature (drag and drop)
	 */
	public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
	{
		if ($order_by && $this->context->cookie->__get($this->table.'Orderby'))
			$order_by = $this->context->cookie->__get($this->table.'Orderby');
		else
			$order_by = 'position';

		parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
	}

	public function postProcess()
	{
		$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id);
		if (Tools::isSubmit('statusconfig_tab') && Tools::getValue($this->identifier))
		{
			if ($this->tabAccess['edit'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()))
				{
					if ($object->toggleStatus())
					{
						$identifier = ((int)$object->id_parent ? '&id_editor='.(int)$object->id_editor : '');
						Tools::redirectAdmin(self::$currentIndex.'&conf=5'.$identifier.'&token='.Tools::getValue('token'));
					}
					else
						$this->errors[] = Tools::displayError('An error occurred while updating status.');
				}
				else
					$this->errors[] = Tools::displayError('An error occurred while updating status for object.')
						.' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->errors[] = Tools::displayError('You do not have permission to edit here.');
		}
		elseif (Tools::isSubmit('position'))
		{
			$object = new ConfigTab((int)Tools::getValue($this->identifier, Tools::getValue('id_editor_to_move', 1)));
			if ($this->tabAccess['edit'] !== '1')
				$this->errors[] = Tools::displayError('You do not have permission to edit here.');
			elseif (!Validate::isLoadedObject($object))
				$this->errors[] = Tools::displayError('An error occurred while updating status for object.')
					.' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
				$this->errors[] = Tools::displayError('Failed to update the position.');
			else
			{
				$identifier = '';
				$token = Tools::getAdminTokenLite('AdminThemeEditor');

				Tools::redirectAdmin(
					self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.$identifier.'&token='.$token
				);
			}
		}
		/* Delete multiple objects */
		elseif (Tools::getValue('submitDel'.$this->table) || Tools::getValue('submitBulkdelete'.$this->table))
		{
			if ($this->tabAccess['delete'] === '1')
			{
				if (Tools::isSubmit($this->table.'Box'))
				{
					$config_tab = new ConfigTab();
					$result = true;
					$result = $config_tab->deleteSelection(Tools::getValue($this->table.'Box'));
					if ($result)
					{
						$config_tab->cleanPositions((int)Tools::getValue('id_editor'));
						$token = Tools::getAdminTokenLite('AdminThemeEditor');
						Tools::redirectAdmin(self::$currentIndex.'&conf=2&token='.$token.'&id_editor='.(int)Tools::getValue('id_editor'));
					}
					$this->errors[] = Tools::displayError('An error occurred while deleting selection.');

				}
				else
					$this->errors[] = Tools::displayError('You must select at least one element to delete.');
			}
			else
				$this->errors[] = Tools::displayError('You do not have permission to delete here.');
		}
		parent::postProcess();
	}
	
	public function renderForm()
	{
		$this->fields_form = array(
			'tinymce' => true,
			'legend' => array(
				'title' => $this->l('Tabs'),
				'image' => '../img/admin/cog.gif'
			),
			'input' => array(
				array(
					'type' => 'select',
					'label' => $this->l('Editor'),
					'name' => 'id_editor',
					'required' => true,
					'options' => array(
						'query' => ThemeEditor::getEditors(),
						'id' => 'id_editor',
						'name' => 'fullname'
					),
					'desc' => $this->l('Select the associated editor.')
				),
				array(
					'type' => 'text',
					'label' => $this->l('Name'),
					'name' => 'name',
					'size' => 33,
					'required' => true,
					'hint' => $this->l('Invalid characters:').' <>;=#{}'
				),
				array(
					'type' => 'text',
					'label' => $this->l('Label'),
					'name' => 'label',
					'size' => 33,
					'lang' => true,
					'required' => true,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}',
					'desc' => $this->l('The label to be displayed in the theme editor interface.')
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Description'),
					'name' => 'description',
					'autoload_rte' => true,
					'lang' => true,
					'rows' => 5,
					'cols' => 40,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}',
					'desc' => $this->l('About the features enabled by this tab.')
				),
				array(
					'type' => 'radio',
					'label' => $this->l('Available'),
					'name' => 'active',
					'required' => false,
					'class' => 't',
					'is_bool' => true,
					'values' => array(
						array(
							'id' => 'active_on',
							'value' => 1,
							'label' => $this->l('Enabled')
						),
						array(
							'id' => 'active_off',
							'value' => 0,
							'label' => $this->l('Disabled')
						)
					),
				),
				array(
					'type' => 'text',
					'label' => $this->l('Iso Lang'),
					'name' => 'lang_iso',
					'size' => 33,
					'readonly' => true,
					'required' => true,
					'lang' => true,
					'desc' => $this->l('This field is authomaticaly fill.'),
				),
			),
			'submit' => array(
				'title' => $this->l('   Save   '),
				'class' => 'button'
			)
		);
        $languages = Language::getLanguages(false);
        $this->fields_value['lang_iso'] = array();
        foreach ($languages AS $lang)
        {
            $this->fields_value['lang_iso'][$lang['id_lang']] = $lang['iso_code'];
        }

		if (!($obj = $this->loadObject(true)))
			return;

		return parent::renderForm();
	}

	public function renderView()
	{
		if (!($object = $this->loadObject()))
			return;
			
		$this->tpl_view_vars = array(
			'id_lang' => Context::getContext()->language->id,
			'object' => $object,
			'head_title' => ($object->id ? $object->label : $this->l('New tab for the editor interface')),
			'shopContext' => Shop::getContext(),
		);

		return parent::renderView();
	}
}